"""
    获取label对上的concept, concept在概念树中的所有父级标签
"""


import json 
import copy
import argparse
import pandas as pd 
from multiprocessing import  Pool


def label_tree_concept_parent(tree_embedding, label_tree_concept, output):
    # 读入概念树并转换为一个字典
    with open(tree_embedding) as file:
        tree = json.load(file)
    tree_dict = {}
    for k,v in tree.items():
        tree_dict[k] = {}
        for k_1,v_1 in v.items():
            v_1_tmp = copy.deepcopy(v_1)
            v_1_tmp["concept"] = v_1_tmp["concept"].strip()
            tree_dict[k][k_1.strip()] = v_1_tmp
            
    with open(label_tree_concept) as file:
        label_tree_concept = json.load(file)
    
    no_match = []
    label_concept_menu = {}
    for k,v in label_tree_concept.items():
        v = v.strip()
        v_menu = ""
        for t_k, t_v in tree_dict.items():
            if v in t_v:
                menu = t_v[v]
                v_menu = {
                    "menu_order": menu["menu_order"],
                    "concept": menu["concept"],
                    "level": menu["level"],
                    "parent": menu["parent"]
                }
                # print( v_menu)
                label_concept_menu[k] = v_menu
                
        if v_menu == "":
            # print(k,"\t",v)
            no_match.append(v_menu)
    # print(len(no_match), "个没有匹配上！")
    # 获取 concept的所有父级标签
    result = {}
    for k,v in label_concept_menu.items():
        v_menu_level = v["level"]
        level_list = list(range(1,v_menu_level+1))
        if len(level_list) == 1:
            result[k] = {
                "level_list": v_menu_level,
                "concepts": v
            } 
        else:
            level_concept = [v["concept"]]
            reverse = list(reversed(level_list[:-1]))
            tmp_parent = v["parent"]
            for i in reverse:
                tmp_menu = tree_dict[str(i)][tmp_parent]
                tmp_concept = tmp_menu["concept"]
                tmp_parent = tmp_menu["parent"]
                level_concept.append(tmp_concept)
                
            result[k] = {
                "level_list": level_list,
                "concepts": level_concept[::-1]
            }
            
    with open(output, "w") as file:
        json.dump(result, file, indent=4)
    print(output)
    
    
def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-tree_embedding","--tree_embedding")
    parser.add_argument("-label_tree_concept","--label_tree_concept")
    parser.add_argument("-output","--output")
    params = parser.parse_args()
    
    return params 


if __name__ == "__main__":
    params = parse_args()
    tree_embedding = params.tree_embedding
    label_tree_concept = params.label_tree_concept
    output = params.output
    
    label_tree_concept_parent(tree_embedding, label_tree_concept, output)
    